﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace Library
{
    public enum Command
    {
        Login,
        Logout,
        Message,
        List,
        Start,
        SanSang,
        Luot,
        CayRac,
        Boc,
        Chot,
        An,
        None
    }
    public class ChatMessage
    {
        public string UserName { get; set; }
        public Command CmdType { get; set; }
        public string Message { get; set; }

        public ChatMessage(string username, Command type, string message)
        {
            UserName = username;
            Message = message;
            CmdType = type;
        }
        public ChatMessage(byte[] bytes)
        {
            this.CmdType = (Command)BitConverter.ToInt32(bytes, 0);

            var UserLen = BitConverter.ToInt32(bytes, 4);
            var MessageLen = BitConverter.ToInt32(bytes, 8);
            this.UserName = UserLen > 0 ?
                Encoding.UTF8.GetString(bytes, 12, UserLen) : "<anynomous>";

            this.Message = MessageLen > 0 ?
                Encoding.UTF8.GetString(bytes, 12 + UserLen, MessageLen) : string.Empty;
        }
        public byte[] TobyteArray()
        {
            List<byte> mang = new List<byte>();
            mang.AddRange(BitConverter.GetBytes((int)this.CmdType));

            var namebytes = Encoding.UTF8.GetBytes(this.UserName);
            //lenght name
            mang.AddRange(BitConverter.GetBytes(namebytes.Length));
            //lenght message

            var messagelen = Encoding.UTF8.GetBytes(this.Message);
            mang.AddRange(BitConverter.GetBytes(messagelen.Length));
            //add bytes name
            mang.AddRange(Encoding.UTF8.GetBytes(this.UserName));
            mang.AddRange(Encoding.UTF8.GetBytes(this.Message));

            return mang.ToArray();
        }
    }
}
